package zju.lzy.controller;

import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureDSA;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import zju.lzy.dto.ResponseMessage;
import zju.lzy.dto.User;
import zju.lzy.mapper.UserMapper;
import zju.lzy.service.user.UserService;
import org.apache.commons.codec.binary.Hex;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

@RestController
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService service;

    @Autowired
    private UserMapper userMapper;



    @PostMapping("/register")
    public ResponseMessage register(@RequestParam(required = false, defaultValue = "") String userName,
                                    String email,
                                    String password) {
        if (userName.length() == 0) {
            userName = service.getAvailableUserName();
        }

        System.out.println(userName+email+password);
        boolean rst = false;
        try{
            rst = userMapper.createUser(userName,email,password);
        }catch (Exception e){
            logger.warn(e.getMessage());
        }
        if(rst){
            // 直接返回查询
            return new ResponseMessage(true,"注册成功",userMapper.getUserByName(userName));
        }
        else{
            return new ResponseMessage(false,"注册失败，用户名或邮箱已存在",-1);
        }


    }

    @PostMapping("/login")
    public ResponseMessage login(String email, String password) {
        List<User> rst = userMapper.fetchUserByEmailAndPwd(email,password);
        if(rst!=null&&rst.size()==1){
            return new ResponseMessage(true,"登录成功！",rst.get(0));
        }
        else{
            logger.info(email+password);
            return new ResponseMessage(false,"登录失败，请检查邮箱及密码！",null);
        }
    }




}
